import React from 'react';
import { Text, Box } from 'ink';
import CodeBlock from './CodeBlock';

interface MarkdownRendererProps {
  content: string;
  theme?: 'dark' | 'light';
}

const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ 
  content, 
  theme = 'dark' 
}) => {
  const parseMarkdown = (text: string) => {
    const lines = text.split('\n');
    const elements: JSX.Element[] = [];
    let i = 0;

    while (i < lines.length) {
      const line = lines[i];

      // 代码块处理
      if (line.trim().startsWith('```')) {
        const language = line.trim().slice(3) || 'text';
        const codeLines: string[] = [];
        i++;

        while (i < lines.length && !lines[i].trim().startsWith('```')) {
          codeLines.push(lines[i]);
          i++;
        }

        elements.push(
          <Box key={i} flexDirection="column" marginY={1}>
            <Box marginBottom={1}>
              <Text color="gray" dimColor>
                {language ? `[${language}]` : '[代码]'}
              </Text>
            </Box>
            <Box paddingLeft={2}>
              <CodeBlock 
                code={codeLines.join('\n')} 
                language={language}
                theme={theme}
              />
            </Box>
          </Box>
        );
        i++;
        continue;
      }

      // 标题处理
      if (line.startsWith('#')) {
        const level = line.match(/^#+/)?.[0].length || 1;
        const title = line.replace(/^#+\s*/, '');
        const color = level === 1 ? 'cyan' : level === 2 ? 'blue' : 'white';
        
        elements.push(
          <Box key={i} marginY={1}>
            <Text color={color} bold={level <= 2}>
              {title}
            </Text>
          </Box>
        );
        i++;
        continue;
      }

      // 列表处理
      if (line.match(/^\s*[-*+]\s/)) {
        const listItems: string[] = [];
        while (i < lines.length && lines[i].match(/^\s*[-*+]\s/)) {
          listItems.push(lines[i].replace(/^\s*[-*+]\s/, ''));
          i++;
        }

        elements.push(
          <Box key={i} flexDirection="column" marginY={1}>
            {listItems.map((item, index) => (
              <Box key={index}>
                <Text color="yellow">• </Text>
                <Text>{processInlineMarkdown(item)}</Text>
              </Box>
            ))}
          </Box>
        );
        continue;
      }

      // 引用处理
      if (line.startsWith('>')) {
        const quoteLines: string[] = [];
        while (i < lines.length && lines[i].startsWith('>')) {
          quoteLines.push(lines[i].replace(/^>\s?/, ''));
          i++;
        }

        elements.push(
          <Box key={i} marginY={1} paddingLeft={2}>
            <Text color="gray">
              {quoteLines.map(line => processInlineMarkdown(line)).join('\n')}
            </Text>
          </Box>
        );
        continue;
      }

      // 普通段落
      if (line.trim()) {
        elements.push(
          <Box key={i} marginY={1}>
            <Text>{processInlineMarkdown(line)}</Text>
          </Box>
        );
      }

      i++;
    }

    return elements;
  };

  const processInlineMarkdown = (text: string): string => {
    // 处理行内代码
    text = text.replace(/`([^`]+)`/g, '[$1]');
    
    // 处理粗体
    text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
    text = text.replace(/__([^_]+)__/g, '$1');
    
    // 处理斜体
    text = text.replace(/\*([^*]+)\*/g, '$1');
    text = text.replace(/_([^_]+)_/g, '$1');
    
    return text;
  };

  return (
    <Box flexDirection="column">
      {parseMarkdown(content)}
    </Box>
  );
};

export default MarkdownRenderer;